package com.p2l.letterblocks;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusOneButton;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences.Editor;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ActivityMain extends Activity implements ConnectionCallbacks, OnConnectionFailedListener  {
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
	private static final int PLUS_ONE_REQUEST_CODE = 0;

	private ProgressDialog dialog;
    private PlusClient client;
    private PlusOneButton plus;
    private ConnectionResult result;
    
	private Integer[] language_drawables;
	
	private SharedPreferences preferences;
	private RelativeLayout background;
	private TypedArray language_array;
	private TextView play, shop, wardrobe, language, credits, logout, settings;
	private ListView language_selection;
	
	private int userId, selected;
	
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.main);
		
		preferences = getSharedPreferences("LetterBlocks", MODE_PRIVATE);
		userId = getIntent().getIntExtra("userId", -1);
		
		background = (RelativeLayout) findViewById(R.id.main_background);
		
		language_array = getResources().obtainTypedArray(R.array.language);
		language_drawables = new Integer[language_array.length()];
		for (int i = 0; i < language_array.length(); i++)
			language_drawables[i] = language_array.peekValue(i).resourceId;
		
		language_selection = (ListView) findViewById(R.id.lstLanguage);
		language_selection.setVisibility(View.INVISIBLE);
		
		LanguageAdapter adapter = new LanguageAdapter(this, R.layout.language_item, language_drawables);
		language_selection.setAdapter(adapter);
		language_selection.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				selected = position;
				language.setBackgroundResource(language_drawables[position]);
				language_selection.setVisibility(View.INVISIBLE);
			}
		});
		
		language = (TextView) findViewById(R.id.btnLanguage);
		language.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (language_selection.getVisibility() == View.INVISIBLE)
					language_selection.setVisibility(View.VISIBLE);
				else
					language_selection.setVisibility(View.INVISIBLE);
			}
		});
		
		play = (TextView) findViewById(R.id.btnPlay);
		play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), ActivityChapter.class);
				intent.putExtra("userId", userId);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
			}
		});
		
		shop = (TextView) findViewById(R.id.btnShop);
		shop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), ActivityShop.class);
				intent.putExtra("userId", userId);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
			}
		});
		
		wardrobe = (TextView) findViewById(R.id.btnWardrobe);
		wardrobe.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), ActivityWardrobe.class);
				intent.putExtra("userId", userId);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
			}
		});
		
		credits = (TextView) findViewById(R.id.btnCredits);
		credits.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogCredits d = new DialogCredits(v.getContext());
				d.show();
			}
		});
		
		logout = (TextView) findViewById(R.id.btnLogout);
		logout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), ActivityLogin.class);
	    		intent.putExtra("login", true);
	    		startActivity(intent);
	    		finish();
			}
		});
		
		settings = (TextView) findViewById(R.id.btnSettings);
		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogSettings d = new DialogSettings(v.getContext());
				d.show();
			}
		});
		
		if (userId == -1) {
			shop.setEnabled(false);
			shop.setBackgroundResource(R.drawable.button_shop_offline);
			wardrobe.setEnabled(false);
			wardrobe.setBackgroundResource(R.drawable.button_wardrobe_offline);
		}
		
		try {
			client = new PlusClient.Builder(this, this, this)
				.clearScopes()
				.build();

	        dialog = new ProgressDialog(this);
	        dialog.setMessage("Signing in...");
	        
			plus = (PlusOneButton) findViewById(R.id.plus_one_button);
        } catch (Exception e) { }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		selected = preferences.getInt("language", getResources().getInteger(R.integer.language));
		language.setBackgroundResource(language_drawables[selected]);
		language_selection.setSelection(selected);
	    plus.initialize(client, "https://play.google.com/store/apps/details?id=" + getPackageName(), PLUS_ONE_REQUEST_CODE);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Editor editor = preferences.edit();
		editor.putInt("language", selected);
		editor.commit();
		language_selection.setVisibility(View.INVISIBLE);
	}

    @Override
    protected void onStart() {
        super.onStart();
        client.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        client.disconnect();
    }
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (background.getBackground() != null)
			background.getBackground().setCallback(null);
		if (play.getBackground() != null)
			play.getBackground().setCallback(null);
		if (shop.getBackground() != null)
			shop.getBackground().setCallback(null);
		if (wardrobe.getBackground() != null)
			wardrobe.getBackground().setCallback(null);
		if (language.getBackground() != null)
			language.getBackground().setCallback(null);
		if (credits.getBackground() != null)
			credits.getBackground().setCallback(null);
		if (logout.getBackground() != null)
			logout.getBackground().setCallback(null);
		
		try {
			for (int i = 0; i < language_selection.getCount(); i++) {
				LinearLayout l = (LinearLayout) language_selection.getChildAt(i);
				ImageView img = (ImageView) l.getChildAt(0);
				if (img.getBackground() != null)
					img.getBackground().setCallback(null);
				l.removeAllViews();
			}
		} catch (NullPointerException e) { }
		
		language_array.recycle();

		language_selection = null;
		language_drawables = null;
		language_array = null;
		preferences = null;
		background = null;
		wardrobe = null;
		language = null;
		credits = null;
		dialog = null;
		client = null;
		logout = null;
		plus = null;
		play = null;
		shop = null;
		
		System.gc();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (language_selection.getVisibility() == View.VISIBLE)
				language_selection.setVisibility(View.INVISIBLE);
			else
				finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private class LanguageAdapter extends ArrayAdapter<Integer> {
		private Integer[] resources;
		
		public LanguageAdapter(Context context, int textViewResourceId, Integer[] resources) {
			super(context, textViewResourceId, resources);
			this.resources = resources;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			return getView(position, convertView, parent);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View view = inflater.inflate(R.layout.language_item, parent, false);
			ImageView image = (ImageView) view.findViewById(R.id.imgLanguage);
			image.setImageResource(resources[position]);
			return view;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
	    if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
	        result = null;
	        client.connect();
	    }
        //client.disconnect();
        //client.connect();
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (dialog.isShowing()) {
			// The user clicked the sign-in button already. Start to resolve
            // connection errors. Wait until onConnected() to dismiss the
            // connection dialog.
            if (result.hasResolution()) {
            	try {
            		result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
            	} catch (SendIntentException e) {
            		client.connect();
            	}
            }
		}

		// Save the intent so that we can start an activity when the user clicks
		// the sign-in button.
		this.result = result;
	}

	@Override
	public void onDisconnected() { }

	@Override
	public void onConnected(Bundle bundle) {
		dialog.dismiss();
	}
	
	/*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.log_off:
    		Intent intent = new Intent(this, ActivityLogin.class);
    		intent.putExtra("login", true);
    		startActivity(intent);
    		finish();
    		return true;
    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }*/
}